#include "syslogin.h"
#include <QDebug>
#include <QPushButton>
#include "baseproto.h"
#include "cgproto.pb.h"
#include "client-socket.h"
#include "userconfigs.h"
#include "client_global.h"

CNS_SYS_REGISTER(SysLogin);

SysLogin::SysLogin()
{

}

void SysLogin::f_start(CnsComponentPtr com)
{
    LoginDialogPtr login = com->propertyInNs("view").value<LoginDialogPtr>();
    UserConfigsPtr userConfigsPtr = com->property("userConfigs").value<UserConfigsPtr>();
    login->setUsername(userConfigsPtr->getValue("login", "username"));
    login->setPasswd(userConfigsPtr->getValue("login", "passwd"));
    login->show();
    login->enable(false);
    connect(login->getBtnLogin(), &QPushButton::clicked,
                      this, [com, login](){
        com->exec("onBtnClicked",
                   Q_ARG(LoginDialogPtr, login));
    });
}


void SysLogin::onBtnClicked_b(CnsComponentPtr com, LoginDialogPtr loginView)
{
    cgproto::LoginRequest lgReq;
    UserConfigsPtr userConfigsPtr = com->property("userConfigs").value<UserConfigsPtr>();
    lgReq.set_username(loginView->getUsername().toUtf8());
    lgReq.set_passwd(loginView->getPasswd().toUtf8());
    userConfigsPtr->setValue("login", "username", loginView->getUsername());
    userConfigsPtr->setValue("login", "passwd", loginView->getPasswd());
    ClientSocketProcPtr clientSocketProcPtr = com->property("clientSocket").value<ClientSocketProcPtr>();
    clientSocketProcPtr->msgSend(ProtoType::LOGIN_REQUEST, static_cast<google::protobuf::Message&>(lgReq));
}

void SysLogin::f__on_read(CnsComponentPtr com, cgproto::Message& msg)
{
    cgproto::LoginResponse lgResp;
    ClientSocketProc *client = CAST_REF_TYPE_FROM_VOID(ClientSocketProc, com.data());
    if(client->getBaseProto().decode(msg.body().c_str(), static_cast<int>(msg.body().size()), lgResp))
    {
        CNSLOG_DEBUG(QString("login response is %1!").arg(lgResp.status().c_str()));
        LoginDialogPtr loginView = com->propertyInNs("view").value<LoginDialogPtr>();
        connect(loginView.data(), &LoginDialog::loginSuccess, loginView.data(), [loginView](){
            CnsComponentPtr mainView = FRAMEWORK->getComponent("/client/.//gnMainWindow");
            mainView->exec("start");
            loginView->close();
        });
        emit loginView->loginSuccess();
    }
}
